package com.qf.utils.filter;

import com.qf.bean.Employee;
import com.qf.bean.Menu;
import com.qf.bean.Role;
import com.qf.dao.MenuMapper;
import com.qf.dao.RoleMapper;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * IntelliJ IDEA -> person
 * 2019/11/26 17:11
 *
 * @author zmyao
 * 别看，我是渣渣。
 */
public class MyForm extends FormAuthenticationFilter {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private MenuMapper menuMapper;
    //认证成功后，就是登录后
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        System.out.println("onLoginSuccess开始");
        Employee employee = (Employee)subject.getPrincipal();
        Role role = roleMapper.selectByPrimaryKey(employee.getRoleid());
        List<Menu> menus = menuMapper.selectMenusByRoleId(role.getRoleid());
        ArrayList<Menu> firstMenuList = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getUpmenuid()== 0 ){
                ArrayList<Menu> secondMenuList = new ArrayList<>();
                for (Menu second : menus) {
                    if (menu.getMenuid() == second.getUpmenuid()) {
                        secondMenuList.add(second);
                    }
                }
                menu.setSecondMenu(secondMenuList);
                firstMenuList.add(menu);
            }
        }
        role.setMenuList(firstMenuList);
        employee.setRole(role);
//        List<Menu> permission = menuMapper.selectPermissionByRoleId(role.getRoleid());
//        role.setPermissionList(permission);
        HttpServletRequest req = (HttpServletRequest) request;
        req.getSession().setAttribute("employee",employee);
        HttpServletResponse resp = (HttpServletResponse) response;
        System.out.println("onLoginSuccess结束");
        resp.sendRedirect("/index.jsp");
        return  false;
     //   return super.onLoginSuccess(token, subject, request, response);
    }
}
